const { Types } = require('mongoose');
const Heartbeat = require('./mongo/heartbeat');
const users = require('./users');

async function keepAlive(uuid, userId, upsert = false) {
  return Heartbeat.updateOne({
    uuid,
    userId: Types.ObjectId(userId),
  }, {
    updatedAt: new Date(),
  }, {
    upsert,
  });
}

async function disconnect(uuid) {
  await Heartbeat.deleteOne({ uuid });
}

async function isUserOnline(userId) {
  const exists = await Heartbeat.countDocuments({
    userId: Types.ObjectId(userId),
  });
  return !!exists;
}

async function getTesterOnlineCount() {
  const ret = await Heartbeat.aggregate([
    {
      $lookup: {
        from: 'users', localField: 'userId', foreignField: '_id', as: 'user',
      },
    },
    {
      $unwind: '$user',
    },
    {
      $match: {
        'user.role': { $bitsAllSet: users.roleKind.tester },
      },
    },
    {
      $group: {
        _id: '$userId',
        connection: { $sum: 1 },
      },
    },
    {
      $count: 'total',
    },
  ]);
  const [{ total }] = ret && ret.length ? ret : [{ total: 0 }];
  return total;
}

module.exports = {
  keepAlive,
  disconnect,
  isUserOnline,
  getTesterOnlineCount,
};
